package com.lagou.edu.controller;

import com.lagou.edu.entity.Resume;
import com.lagou.edu.service.ResumeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/resume")
public class ResumeController {

    private final ResumeService resumeService;

    public ResumeController(ResumeService resumeService) {
        this.resumeService = resumeService;
    }

    @GetMapping("/list")
    public ModelAndView list(ModelAndView mv) {
        final List<Resume> list = resumeService.findAll();
        mv.addObject("list", list);
        mv.setViewName("/resume/list");
        return mv;
    }

    @GetMapping("create")
    public ModelAndView create(ModelAndView mv) {
        mv.addObject(new HashMap<>());
        mv.setViewName("/resume/form");
        return mv;
    }

    @PostMapping()
    public String save(Resume resume) {
        resumeService.save(resume);
        return "redirect:/resume/list";
    }

    @GetMapping("{id}")
    public ModelAndView edit(@PathVariable Long id, ModelAndView mv) {
        Resume resume = resumeService.findById(id);
        mv.addObject("resume", resume);
        mv.setViewName("/resume/form");
        return mv;
    }

    @PostMapping("{id}")
    public String update(@PathVariable Long id, Resume resume) {
        resumeService.save(resume);
        return "redirect:/resume/list";
    }

    @GetMapping("/delete/{id}")
    public String remove(@PathVariable Long id) {
        resumeService.delete(id);
        return "redirect:/resume/list";
    }
}
